<script lang="ts" setup>
import type { Address } from '@/types/medicine'
import { ref, onMounted } from 'vue'
import { getAddressListService } from '@/api/medicine'
import { Toast, type AddressListAddress } from 'vant'
import AddPopup from './components/AddPopup.vue'
import { useRoute, useRouter } from 'vue-router'
import { useMedicineStore } from '@/stores'

const route = useRoute()
const isChange = ref(route.query.isChange === '1')
const addressList = ref<Address[]>()
const choosedAddressId = ref('1')
const getAddressList = async () => {
  const t = Toast.loading({
    message: '加载中...',
    duration: 0,
  })
  try {
    const res = await getAddressListService()
    addressList.value = res
    list.value = res.map((item) => {
      return {
        id: item.id,
        name: item.receiver, // 收货人
        tel: item.mobile, // 手机号
        address: item.province + item.city + (item.county ? item.county : '') + item.addressDetail,
        isDefault: item.isDefault === 1 ? true : false, // 是否默认地址
      }
    })
  } catch (error) {
    Toast.fail('获取地址列表失败')
  } finally {
    t.clear()
  }
}
const list = ref<AddressListAddress[]>()
const show = ref(false)
onMounted(() => {
  getAddressList()
})
const editId = ref('') // 编辑地址id

// 选择地址
const medicineStore = useMedicineStore()
const router = useRouter()
const chooseAddress = (item: AddressListAddress) => {
  if (isChange.value) {
    medicineStore.chooseAddress(item.id as string)
    router.back()
  }
}
</script>

<template>
  <div class="address-page">
    <cp-nav-bar :title="isChange ? '选择地址' : '地址管理'"></cp-nav-bar>

    <van-address-list
      v-model="choosedAddressId"
      :list="list"
      default-tag-text="默认"
      @add="((show = true), (editId = ''))"
      @edit="((show = true), (editId = $event.id))"
      @select="chooseAddress"
    ></van-address-list>
    <div class="address-empty">
      <van-empty v-if="!list?.length" description="暂无地址" />
    </div>
    <!-- 新增地址弹层 -->
    <add-popup v-model:show="show" :id="editId" @refresh="getAddressList"></add-popup>
  </div>
</template>

<style lang="scss" scoped>
.address-page {
  box-sizing: border-box;
  height: 100vh;
  background-color: #f7f8fa;
  padding-top: 46px;
  :deep(.van-address-list__bottom) {
    background-color: transparent;
  }
  .address-empty {
    position: absolute;
    top: 60px;
    left: 50%;
    transform: translateX(-50%);
  }
}
</style>
